package coms.fourthirty.emm.serverproxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import coms.fourthirty.emm.resources.Message;

public class EMSServerProxy {

	private static String serviceAddress = "http://64.113.91.69:8000/nspremo/Service";

	public static boolean login(String username, String password) {
		JSONObject response = executeRequest(serviceAddress + "/logon");
		try {
			return response.get("username").equals(username);
		} catch (JSONException e) {
			return false;
		}
	}

	public static ArrayList<Message> getMessages(String username) {
		JSONObject response = executeRequest(serviceAddress + "/getMessagesTo");
		ArrayList<Message> ret = new ArrayList<Message>();
		try {
			JSONArray messages = response.getJSONArray("messages");
			for (int i = 0; i < messages.length(); i++) {
				ret.add(new Message());
			}
		} catch (JSONException e) {
			
		}
		return ret;
	}

	private static JSONObject executeRequest(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		JSONObject json = new JSONObject();

		HttpResponse response;
		try {

			response = httpclient.execute(httppost);

			HttpEntity entity = response.getEntity();

			if (entity != null) {

				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);

				json = new JSONObject(result);

				instream.close();
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return json;
	}

	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
